package com.boot.filter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.boot.entity.Account;
import com.boot.mapper.AccountMapper;
import lombok.Data;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.PathMatchingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * 实现思路是:在数据库中存储URL地址 并且提前配置好每个URL的权限
 * 在过滤器中 查询请求的URL 和数据库进行匹配:匹配URL和权限 如果能匹配上则放行通过 否则不放行
 *
 */
@Slf4j
@Setter
public class URLPathMatchingFilter extends PathMatchingFilter {

	AccountMapper accountMapper;

	@Override
	protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		String requestURI = getPathWithinApplication(request);
		log.info("requestURI--->{}",requestURI);

		//通过用户名、url、用户拥有的权限 从数据库查询 如果能查询到 说明该用户拥有的权限/角色 具有该URL权限
		//select * from account where userName=? and url=? and (perms = ? or role = ?)
		//目前由于设计 只是简单的将URL放到account表中 所以直接查询:where userName=? and url=?
		Subject subject = SecurityUtils.getSubject();

		Account account = (Account) subject.getPrincipal();

		QueryWrapper<Account> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("username",account.getUsername());
		queryWrapper.eq("url",requestURI);

		Integer count = accountMapper.selectCount(queryWrapper);
		if(count > 0){
			return true;
		}else{
			WebUtils.issueRedirect(request, response, "/unauth");
			return false;
		}
	}
}